//
//  ShoppingViewController.m
//  hehenianMobile
//
//  Created by 余海华 on 16/4/19.
//  Copyright © 2016年 huihu. All rights reserved.
//

#import "ShoppingViewController.h"
#import "BaoController.h"

#import "AppDelegate.h"
#import "UIBarButtonItem+Extension.h"
#import "NSString+extension.h"
#import "UIImage+MJ.h"
#import <MJRefresh/MJRefresh.h>
#import <NJKWebViewProgress.h>
#import <NJKWebViewProgressView.h>
#import "BaoController.h"
#import "AppDelegate.h"
#import "IAuthClient.h"


@interface ShoppingViewController ()<UIWebViewDelegate,UIScrollViewDelegate,NJKWebViewProgressDelegate,UIGestureRecognizerDelegate> {
    
    UIScrollView *_imageViewScrollView;
    NSString* methodString;
    UIView *statView;
    BOOL isloaded;
    BOOL istop;
    
    NSDictionary  *iconDict;// 是否有iCON;
    BOOL isJs;
    UILabel *label;
}

@property(assign,nonatomic) BOOL isRequestCompleted;
/**
 *  scrollView.contentOffset.y
 */
@property(assign,nonatomic) float tempY_old;
/**
 *  scrollView.contentOffset.y
 */
@property(assign,nonatomic) float tempY_new;

@property(nonatomic,strong)  NJKWebViewProgressView *progressView;
@property(nonatomic,weak,readonly) UIControl *share_bgView;
@end

@implementation ShoppingViewController

-(void)layoutUI
{
    for (id view in self.view.subviews) {
        if ([view isKindOfClass:[UIWebView class]]) {
            //[view removeFromSuperview];
            UIWebView *self_WebView=(UIWebView*)view;
            _webView=self_WebView;
        }
    }
    
    if (!_webView) {
        
        UIWebView *webview = nil;
        label = nil;
        
        if (self.headTag == 1) {
            
            if (self.tag != 0) {
                
                webview =[[UIWebView alloc]initWithFrame:CGRectMake(0,0,ScreenWidth,ScreenHeight-44)];
                webview.backgroundColor= IWColor(242.0, 242.0, 242.0);
                [self.view addSubview:webview];
                self.webView=webview;
                
            }else{
                
                webview =[[UIWebView alloc]initWithFrame:CGRectMake(0,64,ScreenWidth,ScreenHeight-44)];
                webview.backgroundColor= IWColor(242.0, 242.0, 242.0);
                [self.tabBarController.view addSubview:webview];
                self.webView=webview;
                
            }
            
        }else if(self.headTag == 0){
            
            [self.navigationController.navigationBar setHidden:YES];
            statView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 20)];
            statView.backgroundColor = IWColor(204, 142, 61);
            [self.tabBarController.view addSubview:statView];
            webview =[[UIWebView alloc]initWithFrame:CGRectMake(0,20,ScreenWidth,ScreenHeight)];
            webview.backgroundColor= IWColor(242.0, 242.0, 242.0);
            [self.tabBarController.view addSubview:webview];
            self.webView=webview;
            
        }
        [[NSURLCache sharedURLCache] removeAllCachedResponses];

        _webView.opaque = NO;//解决bug：内陷在 UIWebView 中部分黑色背景
        
    }
    self.webView.scalesPageToFit = YES;
    _webView.scalesPageToFit = YES;
    _webView.scrollView.backgroundColor=IWColor(242.0, 242.0, 242.0);
    _webView.scrollView.delegate=self;
    
    self.tempY_old=0;
    self.tempY_new=0;
    
}



- (void)viewDidLoad {
    
    [super viewDidLoad];
    self.navigationItem.leftBarButtonItem=[UIBarButtonItem itemWithImageName:@"pr_back-1" highImageName:@"pr_back-1" target:self action:@selector(back:)];
    [self setBarButton];
    isloaded = NO;
    istop = NO;
}




-(void) setBarButton {
    
    UIBarButtonItem *closeItem = [[UIBarButtonItem alloc]initWithTitle:@"关闭" style:UIBarButtonItemStyleBordered target:self action:@selector(closeWebView:)];
    [closeItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} forState:UIControlStateNormal];
    UIBarButtonItem *refreshItem = [UIBarButtonItem itemWithImageName:@"refresh-1" highImageName:@"refresh-1" target:self action:@selector(_selfReloadData)];
    //    UIBarButtonItem  *nullitem=[[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStyleBordered target:self action:@selector(nullSelect)];
    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItems = [NSArray arrayWithObjects:closeItem,refreshItem, nil];
}





-(void) nullSelect {
    
    
}


-(void)closeWebView:(UIBarButtonItem *) sender {
    
    
    [self jumpToHome];
    
}

-(void) navtiveLogin:(NSDictionary *) loginDict {
    
    [MBProgressHUD showText:@"正在登录..." configParameter:^(MBProgressHUD *config) {
        
    } inView:self.view];
    NSString *mobile = [loginDict valueForKey:@"mobile"];
    NSString *password = [loginDict valueForKey:@"password"];
    
    @weakify(self);
    [GetCoreI(IAuthClient) requestLoginWithUserName:mobile password:password code:@"" SuccBlock:^(void) {
        @strongify(self);
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        [CommonFileUtils writeObject:@1 toDocumentPath:@"isLogin"];
        [self.navigationController dismissViewControllerAnimated:YES completion:^(void) {
            
            if (self.successBlock) {
                self.successBlock();
            }
        }];
        
//        [[AppDelegate appDelegate] setTagsAlias];
        
    }failBLock:^(NSString *msg) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        
        
        [MBProgressHUD showTextOnly:[NSString stringWithFormat:@"登录失败:%@",msg] toView:self.view];
        
    }];
}

-(void) BindingPhone {
    
    [self.navigationController dismissViewControllerAnimated:YES completion:^(void) {
        
        if (self.successBlock) {
            self.successBlock();
        }
    }];
    
//    [[AppDelegate appDelegate] setTagsAlias];
    
}

-(void) setTopNavigateIcon:(NSDictionary*) dataDict {
    
    iconDict = dataDict;
    UIImageView *imageView  =  [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    imageView.layer.masksToBounds = YES;
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.clipsToBounds = YES;
    [imageView sd_setImageWithURL:[NSURL URLWithString:[dataDict valueForKey:@"icon"]]];
    imageView.layer.cornerRadius = 15.0f;
    imageView.layer.masksToBounds = YES;

    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showVipDetail)];
    [imageView addGestureRecognizer:tap];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem  alloc] initWithCustomView:imageView];
    
}

-(void)  showVipDetail {
    
    [self.bridge callHandler:@"setTopBarIconCalljs" data:NULL responseCallback:^(id responseData){
        
        
        
    }];
}

-(void) showNav:(NSString *) navTitle andSelect:(NSString*) aSelect {
    
    methodString = aSelect;
    
    if (!label) {
         label = [[UILabel alloc] initWithFrame:CGRectMake(ScreenWidth - 50,0, 50, 44)];
    }

    label.userInteractionEnabled = YES;
    label.textAlignment = NSTextAlignmentCenter ;
    label.backgroundColor = IWColor(255.0, 255.0, 255.0);
    label.text = navTitle;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(edit)];
    [label addGestureRecognizer:tap];
    [self.navigationController.navigationBar addSubview:label];
    [self.navigationController.navigationBar bringSubviewToFront:label];
//    self.navigationItem.rightBarButtonItem =[[UIBarButtonItem alloc]initWithTitle:navTitle style:UIBarButtonItemStyleBordered target:self action:@selector(edit)];
//    [self.navigationItem.rightBarButtonItem setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor]} forState:UIControlStateNormal];
    
}


-(void) setNavigateTitle:(NSString *) title {
    
    if (title.length > 1) {
        
        self.title = title;
    }
}


-(void)edit{
    
    [self.bridge callHandler:methodString data:nil responseCallback:^(id response) {
        NSLog(@"testJavascriptHandler responded: %@", response);
    }];
    
}

-(void)viewWillAppear:(BOOL)animated
{
    
    [self.tabBarController.tabBar setHidden:YES];
    [super viewWillAppear:animated];
    
}


-(void) layoutProgress {
    
    _progressProxy = [[NJKWebViewProgress alloc] init];
    _webView.delegate = _progressProxy;
    _progressProxy.webViewProxyDelegate = self;
    _progressProxy.progressDelegate = self;
    
    CGFloat progressBarHeight = 2.f;
    CGRect navigationBarBounds = self.navigationController.navigationBar.bounds;
    CGRect barFrame = CGRectMake(0, navigationBarBounds.size.height - progressBarHeight, navigationBarBounds.size.width, progressBarHeight);
    _progressView = [[NJKWebViewProgressView alloc] initWithFrame:barFrame];
    _progressView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
    [self.navigationController.navigationBar addSubview:_progressView];
    
}


-(void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
    [self.navigationController.navigationBar setHidden:NO];
    [_progressView removeFromSuperview];
}

/**
 *  加载Web数据
 */
-(void)loadWebWithUrl:(NSString *)strUrl
{
    LogDebug(TBaseWeb,@"loadWebWithUrl(%@):%@ ",self,strUrl);
    if (!_webView) {
        [self layoutUI];
    }
    
    NSURL *URL=[NSURL URLWithString:strUrl];
    
    //2.创建请求
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:URL];
    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:[NSString stringWithFormat:@"%@ %@ (%@; %@ %@; %@)- %@", [[HHNUtility appName] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding], [HHNUtility appVersion], [HHNUtility DeviceVersion], [HHNUtility systemName], [HHNUtility systemVersion],[HHNUtility LocaleLanguage],requestSetUserAgent], @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
    if(![HHNUtility ConnectionAvailable])
    {
        [MBProgressHUD showTextOnly:@"请检查网络连接" toView:self.webView];
        return;
    }
    
    //加载指示器
    _isRequestCompleted=NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!_isRequestCompleted) {//0.3秒后判断是否完成请求，没有完成才加载指示器
            
            [MBProgressHUD showText:@"拼命加载中..." configParameter:^(MBProgressHUD *config) {
                
            } inView:self.webView];
        }
        
    });
    [self.webView loadRequest:request];
    
    
}

/**
 *  重新加载数据
 */
-(void)_selfReloadData
{
    
    if(![HHNUtility ConnectionAvailable])
    {
        MBProgressHUD *hud=[MBProgressHUD HUDForView:self.webView];
        if (!hud) {
            hud=[MBProgressHUD showText:nil configParameter:^(MBProgressHUD *config) {} inView:self.webView];
        }
        hud.mode=MBProgressHUDModeText;
        hud.labelText = @"请检查网络连接";
        [hud hide:YES afterDelay:2.0f];
        [self jumpToHome];
    }
    
    [_webView reload];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 实现代理UIWebViewDelegate

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{

    LogDebug(TBaseWeb, @"shouldStartLoadWithRequest,URL.relativeString(%@):%@",self,request.URL.relativeString);
    HHLog(@"[url scheme] = %@",[[request URL] scheme]);
    [self setBarButton];
    NSString * url = [[request URL] absoluteString];
    NSString *parameters = [url stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *navTitle = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    if (navTitle) {
        [self setNavigateTitle:navTitle];
    }
    if (label) {
        
        [label removeFromSuperview];
        label = nil;
    }
   if([request.URL.relativeString myContainsString:@"/community/login.html"] || [request.URL.relativeString myContainsString:@"/login/index.do"])
    {
        if ([self.link2 myContainsString:@"/account/regIndex.do"]) {
            [self.navigationController popViewControllerAnimated:YES];
            return NO;
        }
        @weakify(self);
//        LoginViewController *loginVC = [[LoginViewController alloc] initCancelBlock:^(void) {
//            @strongify(self);
//            [self jumpToHome];
//        }andSuccessBlock:^(void) {
//            @strongify(self);
//            [self jumpToHome];
//        }andFaileBlock:^(void) {
//            
//            
//        }];
        
//        DHNavigationViewController *navigationVC=[[DHNavigationViewController alloc] initWithRootViewController:loginVC];
//        [self.view.window.rootViewController presentViewController:navigationVC animated:YES completion:nil];
        return NO;
    }else if([request.URL.relativeString myContainsString:@"/login/loginout.do"]){
        //退出登录，清空cookie,用户名...
        [CommonFileUtils deleteObjectFromUserDefaultWithKey:@"userName"];
        [CommonFileUtils deleteFileFromDocumentPath:@"userInfo"];
        //清空Cookie
        NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        NSArray *_tmpArray = [NSArray arrayWithArray:[cookieStorage cookies]];
        for (id obj in _tmpArray) {
            [cookieStorage deleteCookie:obj];
        }
        
//        LoginViewController *loginVC=[[LoginViewController alloc]init];
//        loginVC.delegate=self;
////        
//        DHNavigationViewController *navigationController = [[DHNavigationViewController alloc] initWithRootViewController:loginVC];
//        [self.view.window.rootViewController presentViewController:navigationController animated:YES completion:nil];
        
        
        return NO;
    }else if ([request.URL.relativeString myContainsString:@"/community/ad_list.html"]) {
        
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithImageName:@"add_icon" highImageName:@"add_icon" target:self action:@selector(addHome:)];
        
    }else if([request.URL.relativeString myContainsString:@"/shop/:backApp"]) {
        
        [self jumpToHome];
        return NO;
    }
    
    return YES;
    
}


- (UIViewController*)topViewController
{
    return [self topViewControllerWithRootViewController:self.view.window.rootViewController];
}

- (UIViewController*)topViewControllerWithRootViewController:(UIViewController*)rootViewController
{
    if ([rootViewController isKindOfClass:[UITabBarController class]]) {
        UITabBarController *tabBarController = (UITabBarController *)rootViewController;
        return [self topViewControllerWithRootViewController:tabBarController.selectedViewController];
    } else if ([rootViewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController* navigationController = (UINavigationController*)rootViewController;
        return [self topViewControllerWithRootViewController:navigationController.visibleViewController];
    } else if (rootViewController.presentedViewController) {
        UIViewController* presentedViewController = rootViewController.presentedViewController;
        return [self topViewControllerWithRootViewController:presentedViewController];
    } else {
        return rootViewController;
    }
}



-(void) addHome:(id) sender {
    
    BaoController *baoVc = [[BaoController alloc] initWithUrl:@"http://capi.hehenian.com/page/community/ad_add.html?fromUrl=cdlist" title:@"我的住宅"];
    [self.navigationController pushViewController:baoVc animated:YES];
    
}



-(void)webViewDidStartLoad:(UIWebView *)wv{
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
    
}


-(void)webViewDidFinishLoad:(UIWebView *)wv{
    LogDebug(TBaseWeb, @"Request succ(%@)",self);
    if ([wv.request.URL.relativeString myContainsString:@"https://yintong.com.cn/llpayh5/index.html#/index"]) {
        isloaded = YES;
    }
    _isRequestCompleted=YES;
    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
    [MBProgressHUD hideHUDForView:self.webView animated:YES];

    NSString *navTitle = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    if (navTitle) {
        [self setNavigateTitle:navTitle];
    }
    
}
-(void)webView:(UIWebView *)wv didFailLoadWithError:(NSError *)error {
    
    
    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
    _isRequestCompleted=YES;
    MBProgressHUD *hud=[MBProgressHUD HUDForView:self.webView];
    if (!hud) {
        hud=[MBProgressHUD showText:nil configParameter:^(MBProgressHUD *config) {} inView:self.webView];
    }
    hud.mode=MBProgressHUDModeText;
    if([error code] == NSURLErrorCancelled)
    {
        [hud hide:YES];
        return;
    }
    
    if(![HHNUtility ConnectionAvailable])
    {
        [self jumpToHome];
        hud.labelText = @"请检查网络连接";
        
    }else{
        
        hud.labelText = @"加载失败！";
        LogError(TBaseWeb, @"request failed error(%@ ):%@",self,error.localizedDescription);
    }
    [hud hide:YES afterDelay:2.0f];
    
    //       [self jumpToHome];
}

#pragma mark - NJKWebViewProgressDelegate
-(void)webViewProgress:(NJKWebViewProgress *)webViewProgress updateProgress:(float)progress
{
    HHLog(@"progress=%.2f",progress);
    [_progressView setProgress:progress animated:YES];
}


-(void)back:(id)sender
{
    BOOL isCanGoBack = self.webView.canGoBack;
    if (isCanGoBack) {
        

        if (label) {
            
            [label removeFromSuperview];
            label = nil;
        }
        
        if (isloaded) {
            [self.webView stringByEvaluatingJavaScriptFromString:@"angular.element(document.querySelector('[ng-controller=\"CashierInitCtrl\"]')).scope().openExit()"];
            isloaded = NO;
            istop = YES;
            return;
        }
        if (istop) {
            istop = NO;
            [self closeWebView:nil];
            return;
        }
    
        [self.webView goBack];

    }else{
        
        if (self.navigationController.viewControllers.count > 1) {
            [_webView removeFromSuperview];
            _webView = nil;
            [self.navigationController popViewControllerAnimated:YES];
            return;
        }
        [self.tabBarController.tabBar setHidden:NO];
        [_webView removeFromSuperview];
        _webView = nil;
        AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//        [tempAppDelegate.tabbarController setSelectedIndex:0];
        //登录成功,
        NSDictionary *dict=@{@"index":@"0"};
        //创建  发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"itemSelected" object:nil userInfo:dict];
        return;
    }
}


/**
 *  跳转到首页
 */
-(void)jumpToHome
{
    
    [self.tabBarController.tabBar setHidden:NO];
    if (self.tag != 0) {
        
        [statView removeFromSuperview];
        statView = nil;
        [_webView removeFromSuperview];
        _webView = nil;
        if (label) {
            [label removeFromSuperview];
            label = nil;
        }
        [self.navigationController popViewControllerAnimated:YES];
        
        
    }else {
        if (label) {
            [label removeFromSuperview];
            label = nil;
        }
        [statView removeFromSuperview];
        statView = nil;
        [_webView removeFromSuperview];
        _webView = nil;
        AppDelegate *tempAppDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
//        [tempAppDelegate.tabbarController setSelectedIndex:0];
        //登录成功,
        NSDictionary *dict=@{@"index":@"0"};
        //创建  发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:@"itemSelected" object:nil userInfo:dict];
        
    }
    
    
}



-(void) dealloc {
//    [self.webView removeAllSubviews];
    [self.webView removeFromSuperview];
    self.webView = nil;
    if (label) {
        [label removeFromSuperview];
        label = nil;
    }
    
}


@end
